package cn.xsly.system.controller;

import cn.xsly.system.service.IMenuService;
import cn.xsly.system.domain.Menu;
import cn.xsly.system.query.MenuQuery;
import cn.xsly.basic.util.AjaxResult;
import cn.xsly.basic.util.PageList;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 后端接口类；
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    public IMenuService menuService;

    /**
     * 接口：添加或修改
     *
     * @param menu 传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Menu menu) {
        try {
            if (menu.getId() != null)
                menuService.update(menu);
            else
                menuService.add(menu);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "操作失败");
        }
    }

    /**
     * 接口：删除
     *
     * @param id
     * @return AjaxResult 响应给前端
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            menuService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败");
        }
    }

    /**
     * 接口：批量删除
     *
     * @param ids
     * @return AjaxResult 响应给前端
     */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids) {
        try {
            menuService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "批量删除失败");
        }
    }

    /**
     * 接口：查询单个对象
     *
     * @param id
     */
    @GetMapping("/{id}")
    public Menu findOne(@PathVariable("id") Long id) {
        return menuService.findById(id);
    }


    /**
     * 接口：查询所有
     *
     * @return
     */
    @GetMapping
    public List<Menu> findAll() {
        return menuService.findAll();
    }


    /**
     * 接口：分页查询或高级查询
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping
    public PageList<Menu> queryPage(@RequestBody MenuQuery query) {
        return menuService.queryPage(query);
    }

    /**
     * 查询菜单树
     *
     * @return
     *
     */
    @GetMapping("/menuTree")
    @ApiOperation(value = "获取菜单树-无限极接口")
    public List<Menu> menuTree() {
        return menuService.menuTree();
    }
}